/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChatPanel.java
 *
 * Created on Dec 24, 2008, 12:28:03 AM
 */
package gui.panels;

import gui.HTMLPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author takeshi
 */
public class ChatPanel extends javax.swing.JPanel {

    private final DefaultListModel listModel = new DefaultListModel();
    private final HTMLPanel htmlPanel = new HTMLPanel();
    private final String userName;
    private final String host;
    private final ActionListener sendMessageActionListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = jTextField1.getText();
            if (text.length() > 0) {
                String msg = String.format("[%s] %s", userName, text);
                jTextField1.setText("");
                sendMessage(msg);
            }
        }
    };

    public ChatPanel() {
        this(System.getProperty("user.name", "<unnamed>"), findHost());
    }

    /** Creates new form ChatPanel */
    public ChatPanel(final String userName, String host) {
        this.userName = userName;
        this.host = host;
        initComponents();
    }

    protected void sendMessage(String message) {
        throw new AbstractMethodError();
    }

    protected void linkClicked(String link) {
        throw new AbstractMethodError();
    }

    protected final void appendLink(String url, String text) {
        final Document document = getHtmlPanel().getDocument();
        Element el = document.createElement("a");
        Attr att = document.createAttribute("href");
        att.setNodeValue(url);
        el.appendChild(document.createTextNode(text));
        appendNode(el);
    }

    protected final void appendNode(Node node) {
        getHtmlPanel().getDocument().getElementsByTagName("body").item(0).appendChild(node);
        getHtmlPanel().reloadDocument(getHtmlPanel().getDocument());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = htmlPanel ;
        jButton1 = new javax.swing.JButton();

        jSplitPane1.setDividerLocation(700);
        jSplitPane1.setOneTouchExpandable(true);

        jList1.setModel(listModel);
        jScrollPane1.setViewportView(jList1);

        jSplitPane1.setRightComponent(jScrollPane1);

        jTextField1.registerKeyboardAction(sendMessageActionListener, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);

        jButton2.setMnemonic('S');
        jButton2.setText("Send");
        jButton2.addActionListener(this.sendMessageActionListener);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 764, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanel2);

        jButton1.setMnemonic('C');
        jButton1.setText("Clear");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 676, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 802, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-
        final Document doc = htmlPanel.getDocument();
        final Node content = doc.getElementsByTagName("body").item(0);
        NodeList list = content.getChildNodes();
        for (int i = list.getLength() - 1; i >= 0; i--) {
            content.removeChild(list.item(i));
        }
        htmlPanel.reloadDocument(doc);
    }// GEN-LAST:event_jButton1ActionPerformed

    public final DefaultListModel getListModel() {
        return listModel;
    }

    protected static String findHost() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ex) {
            return "localhost";
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    public void changeMembers(List<String> newMembers) {
        this.listModel.removeAllElements();
        for (String member : newMembers) {
            this.listModel.addElement(member);
        }
    }

    public final HTMLPanel getHtmlPanel() {
        return htmlPanel;
    }
}
